package com.bytemonster.last;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Scope("prototype")
public class TcpLast extends ChannelInboundHandlerAdapter  {

    public static ChannelGroup channelGroups = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx)  {
        log.info("客服端新连接加入：{}",ctx.channel().id());
        channelGroups.add(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.info("客服异常断开: {}，原因: {}",ctx.channel().id(),cause.getMessage());
        closeChannel(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx)  {
        log.info("客服端连接断开：{}",ctx.channel().id());
        closeChannel(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof ByteBuf byteBuf) {
            // 将 ByteBuf 转换为字符串
            String message = byteBuf.toString(CharsetUtil.UTF_8);
            log.info("客服端：{} 发送消息：{}", ctx.channel().id(), message);
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer("服务端收到您发送的信息：" + message, CharsetUtil.UTF_8));
        } else {
            log.info("客服端：{} 发送未知类型的消息：{}", ctx.channel().id(), msg);
        }
    }

    private void closeChannel(ChannelHandlerContext ctx) {
        channelGroups.remove(ctx.channel());
        ctx.close();
    }

}